package org.example.test7;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Properties;

@WebServlet("/doRegisterServlet")
public class DoRegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 读取并写入用户数据
        Properties prop = new Properties();
        String filePath = getServletContext().getRealPath("/user.properties"); // 获取文件真实路径
        File file = new File(filePath);

        // 读取已有用户（若文件存在）
        if (file.exists()) {
            try (InputStream is = new FileInputStream(file)) {
                prop.load(is);
            }
        }

        // 检查用户名是否已存在
        if (prop.containsKey(username)) {
            response.getWriter().write("<script>alert('用户名已存在！'); window.location.href='register.jsp';</script>");
            return;
        }

        // 保存新用户
        prop.setProperty(username, password);
        try (OutputStream os = new FileOutputStream(file)) {
            prop.store(os, "User Data"); // 写入文件
        }

        // 注册成功，跳转到登录页
        response.getWriter().write("<script>alert('注册成功，请登录！'); window.location.href='login.jsp';</script>");
    }
}